var timeouts = new Array();

var countries = {
  us: 'amazon.com',
  uk: 'amazon.co.uk',
  ca: 'amazon.ca',
  de: 'amazon.de',
  fr: 'amazon.fr'
};

var categories = new Object;
categories['1036592']   = "Apparel & Accessories";
categories['1065836']   = "Audio & Video";
categories['15684181']  = "Automotive";
categories['165796011'] = "Baby";
categories['3760911']   = "Beauty";
categories['1057792']   = "Bed & Bath";
categories['283155']    = "Books";
categories['502394']    = "Camera & Photo";
categories['301185']    = "Cell Phones & Service";
categories['1036592']   = "Clothing & Accessories";
categories['468642']    = "Computer & Video Games";
categories['541966']    = "Computers & PC Hardware";
categories['130']       = "DVD";
categories['172282']    = "Electronics";
categories['1057794']   = "Furniture & Decor";
categories['3370831']   = "Gourmet Food";
categories['16310101']  = "Grocery";
categories['3760901']   = "Health & Personal Care";
categories['1055398']   = "Home & Garden";
categories['16310091']  = "Industrial & Scientific";
categories['3367581']   = "Jewelry & Watches";
categories['284507']    = "Kitchen & Housewares";
categories['599858']    = "Magazines & Newspapers";
categories['5174']      = "Music";
categories['11091801']  = "Musical Instruments";
categories['1064954']   = "Office Products";
categories['286168']    = "Outdoor Living";
categories['12923371']  = "Pet Supplies";
categories['1040668']   = "Shoes";
categories['13993911']  = "Shorts by Amazon";
categories['229534']    = "Software";
categories['3375251']   = "Sports & Outdoors";
categories['228013']    = "Tools & Hardware";
categories['165793011'] = "Toys & Games";
categories['16261631']  = "Unbox Video Downloads";
categories['404272']    = "VHS";
categories['916520']    = "Books";
categories['916514']    = "Music";
categories['917972']    = "DVD";
categories['916518']    = "Video";
categories['3198031']   = "Computer & Video Games";
categories['3198021']   = "Software";
categories['59624031']  = "Baby";
categories['266239']    = "Books";
categories['11052651']  = "DIY";
categories['283926']    = "DVD";
categories['560798']    = "Electronics";
categories['11052671']  = "Garden";
categories['11052661']  = "Health";
categories['11052591']  = "Home";
categories['10709121']  = "Houseware";
categories['328228011'] = "Jewellery";
categories['3147441']   = "Kitchen";
categories['11052681']  = "Kitchen";
categories['229816']    = "Music";
categories['300703']    = "PC";
categories['355005011'] = "Shoes";
categories['300435']    = "Software";
categories['318949011'] = "Sports";
categories['468292']    = "Toys";
categories['573398']    = "Video";
categories['12955971']  = "Baby & Kleinkind";
categories['355007011'] = "Baby-Ausstattung";
categories['12956501']  = "Brettspiele";
categories['301929']    = "Bücher";
categories['700962']    = "Computer & Zubehör";
categories['284266']    = "DVD";
categories['562066']    = "Elektronik";
categories['573634']    = "English Books";
categories['16435161']  = "Fashion & Style";
categories['16435171']  = "Fitness";
categories['301052']    = "Games";
categories['10925031']  = "Garten & Freizeit";
categories['10925021']  = "Heimwerken";
categories['11052871']  = "Kamera & Foto";
categories['146800011'] = "Kinder-DVDs";
categories['280652']    = "Kinderbücher";
categories['10925041']  = "Drogerie & Bad";
categories['3167641']   = "Küche & Haushalt";
categories['12955961']  = "Modelle & Fahrzeuge";
categories['290380']    = "Musik";
categories['355006011'] = "Schuhe & Handtaschen";
categories['301928']    = "Software";
categories['12950651']  = "Spielwaren";
categories['16435051']  = "Sport & Freizeit";
categories['16435051']  = "Sportartikel";
categories['327472011'] = "Uhren";
categories['301050']    = "Video";
categories['1161658']   = "Zeitschriften";
categories['301061']    = "Livres";
categories['52042011']  = "Livres en Anglais";
categories['13921051']  = "Image & Son Mirco & Photo";
categories['301062']    = "Musique";
categories['405322']    = "DVD";
categories['530488']    = "Logiciels";
categories['530490']    = "Jeux video";
categories['322086011'] = "Jeux et Jouets";
categories['57004031']  = "Cuisine & Maision";
categories['60649031']  = "Montres & Bijoux";

/* Guess that if there are keywords, the user wants to sort by relevance */
function sort_by_to_relevance() {
  if (document.amazon_discount.keywords.value != '' &&
      document.amazon_discount.sort.selectedIndex == 0) {
    document.amazon_discount.sort.selectedIndex = 1;
  }
}

function add_sort_by_to_relevance() {
  document.amazon_discount.keywords.onfocus=sort_by_to_relevance;
  document.amazon_discount.keywords.onblur=sort_by_to_relevance;
  document.amazon_discount.keywords.onkeypress=sort_by_to_relevance;
  document.amazon_discount.keywords.onkeyup=sort_by_to_relevance;
}

function country_change() {
  var country = get_country();
  for (var node_country in countries) {
    var country_node_id = '#node-' + node_country;
    if (node_country == country) {
      $(country_node_id).show();
    } else {
      $(country_node_id).hide();
    }
  }
}

function get_country() {
  var country;
  for (var x=0;x<document.amazon_discount.country.length;x++) {
    if (document.amazon_discount.country[x].checked) {
      country = document.amazon_discount.country[x].value;
      break;
    }
  }
  return country;
}

function prepare_form() {
  add_sort_by_to_relevance();
  country_change();
  searches.display_urls();
}

function find_amazon_discounts(){
  var prime = null;
  if(document.amazon_discount.prime.checked == true) {
    prime = document.amazon_discount.prime.value;
  } else {
    prime = "";
  }

  var keywords= null;
  if(document.amazon_discount.keywords.value != null) {
    keywords="&keywords="+document.amazon_discount.keywords.value;
  }

  var country = get_country();
  var domain = countries[country];
  var node_ele = document.getElementById('node-' + country);
  var node = node_ele.options[node_ele.selectedIndex].value;
  var url = 'http://' + domain + '/gp/search/?node=' + encodeURIComponent(node)
          + '&pct-off=' + document.amazon_discount.from.value + '-'
          + document.amazon_discount.to.value + prime +'&tag=igamzn-20'
          + document.amazon_discount.sort.value + keywords;
  searches.add_url(url);
  window.open( url );
}

/* A library of cookie functions */
var Cookie = {
  set: function(name, value, daysToExpire) {
    var expires = '';
    if (daysToExpire == undefined) {
      daysToExpire = '365';
    }

    var d = new Date();
    d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
    expires = d;

    var path;
    var domain;
    var secure;
    var curCookie = name + "=" + escape(value) + 
      ((expires) ? "; expires=" + expires.toGMTString() : "") + 
      ((path) ? "; path=" + path : "") + 
      ((domain) ? "; domain=" + domain : "") + 
      ((secure) ? "; secure" : ""); 
    return (document.cookie = curCookie);
  },

  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*'
                + escape(name)
                + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : undefined);
  },

  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },

  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  },

  available: function() {
    var whole_cookie = unescape(document.cookie);
    var cookie_names = new Array;
    var each_cookie = whole_cookie.split(";");
    for(i=0; i<each_cookie.length;i++) {
      var cookie_parts = each_cookie[i].split("=");
      cookie_names.push(cookie_parts[0]);
    }
    return(cookie_names);
  }
};

var searches = {

  data: [],

  /* Retrieves the information from the cookie in the form of an object/array */
  load_from_cookie: function (cookie_name) {

    var value = Cookie.get(cookie_name);
    if (value && value != undefined) {
      searches.data = JSON.parse(unescape(value));
    }
    return;
  },

  /*
  Usage     : searches.add_url(url)
  Purpose   : Adds the url to the array of recent searches and saves the updated
            : array to the cookie.
  Returns   : nothing
  Parameters: none
  Comments  : none
  See Also  : searches.save_urls_to_cookie
  */
  add_url: function (url) {
    if (searches.data[0] == url) {
      return;
    }

    searches.data.unshift(url);
    searches.data = searches.data.splice(0, 10);

    searches.save_urls_to_cookie();
    searches.display_urls();
  },

  /* Saves the information currently in searches.saved_searches to the
     saved cookie */
  save_urls_to_cookie: function () {
    if(searches.data) {
      var dataString = escape(JSON.stringify(searches.data));
      Cookie.set("recent_amazon_searches", dataString);
    }
  },

  display_urls: function() {
    searches.load_from_cookie('recent_amazon_searches');
    if(!searches.data.length) {
      return;
    }

    var text = "";
    for(var i=0; i<searches.data.length; i++) {
      var keyword_regex  = /keywords=(.*?)$/;
      var category_regex = /node=(\d+)/;
      var discount_regex = /pct-off=([-\d]+)/;

      var keyword = keyword_regex.exec(searches.data[i])[1];
      var category_id = category_regex.exec(searches.data[i])[1]
      var category    = categories[category_id];
      var discount    = discount_regex.exec(searches.data[i])[1];

      var link_text = keyword + " " + category + " " + discount;
      var new_link = "<a href='" + searches.data[i] + "' target='_blank'>" + link_text + "</a>";
      if (i < searches.data.length -1) {
        new_link = new_link + " - ";
      }
      text = text + new_link;
    }

    $("#recent_amazon_searches_row").show();
    $("#recent_amazon_searches").html(text);
    return;
  }
}
